package com.hwua.dao.Impl;

import com.hwua.Util.C3P0Util;
import com.hwua.dao.IShopCartDao;
import com.hwua.entity.Product;
import com.hwua.entity.ProductExtend;
import com.hwua.entity.ShopCart;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class ShopCartDaoImpl implements IShopCartDao {
    private QueryRunner queryRunner=null;

    public ShopCartDaoImpl() {
        queryRunner=new QueryRunner(C3P0Util.getCpds());
    }

    @Override
    public int insert(ShopCart shopCart) throws Exception {
        String sql="insert into amz_shop_cart values(null,?,?,?)";
        Object[] args={shopCart.getPid(),shopCart.getPnum(),shopCart.getUid()};
        return queryRunner.update(sql,args);
    }

    @Override
    public List<ProductExtend> queryShopCartByuid(int uid) throws Exception {
        String sql="SELECT\n" +
                "p1.*\n" +
                "FROM\n" +
                "amz_product AS p1,\n" +
                "amz_shop_cart AS p2\n" +
                "WHERE\n" +
                "p1.id=p2.pid\n" +
                "and p2.uid=?";
        Object[] args={uid};
        return queryRunner.query(sql,new BeanListHandler<ProductExtend>(ProductExtend.class),args);
    }

    @Override
    public int delShopCart(int id) throws Exception {
        String sql="delete from amz_shop_cart where pid=?";
        Object[] args={id};
        return queryRunner.update(sql,args);
    }


    @Override
    public List<ShopCart> getBypid(int pid) throws SQLException {
        String sql="SELECT\n" +
                "*\n" +
                "FROM\n" +
                "amz_shop_cart\n" +
                "WHERE\n" +
                "pid=?\n";
        Object[] args={pid};
        return queryRunner.query(sql,new BeanListHandler<ShopCart>(ShopCart.class),args);
    }

    @Override
    public int updateShopCartItem(ShopCart shopCart) throws SQLException {

        String sql="update amz_shop_cart set pnum=? where pid=?";
        Object[]args={shopCart.getPnum(),shopCart.getPid()};
        return queryRunner.update(sql,args);
    }




}
